package com.hjm.app.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.hjm.app.R;
import com.hjm.app.adapter.HomeBannerAdapter;
import com.hjm.java.entity.Goods;
import com.hjm.java.entity.HomeBanner;
import com.hjm.java.entity.Order;
import com.hjm.java.utils.HjmFailCallBack;
import com.hjm.java.utils.HjmSuccessObjectCallBack;
import com.hjm.ui.common.Cell;
import com.hjm.ui.common.ImageLabel;
import com.hjm.ui.goods.GoodsComment;
import com.hjm.ui.goods.GoodsIntro;
import com.hjm.ui.goods.GoodsStoreIntro;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;

import java.util.ArrayList;
import java.util.List;

public class GoodsDetailActivity extends BaseActivity {

    private static final String TAG = "GoodsDetailActivity";
    private List<HomeBanner> bannerList;
    private Banner banner;
    private WebView webViewGoodsDetail;
    private GoodsIntro goodsIntro;
    private Cell cellGoodsType;
    private GoodsStoreIntro goodsStoreIntro;
    private TextView addToShopCart, buyNow;
    private GoodsComment goodsComment;
    private ImageLabel storeImageLabel;
    private ImageButton backImageButton,shopCartImageButton;
    private int typeIndex = 0;

    private Goods goods;
    private int goodsId;
    private boolean isWebViewPageFinished = false;


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        goodsId = intent.getIntExtra("goodsId", 0);
        getGoods(goodsId);
    }

    @Override
    void initView() {
        // 获取传过来的id
        goodsId = getIntent().getIntExtra("goodsId", 0);
        Log.d(TAG, "initView: goodsId = " + goodsId);
        initGoodsIntro();
        initGoodsType();
        initBanner();
        initWebView();
        initBottom();
        initComment();
        storeImageLabel = findViewById(R.id.image_label_store);
        storeImageLabel.setOnclickListener((v) -> {
            Intent intent = new Intent(this, StoreActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (goods != null)
                intent.putExtra("storeId", goods.getStore());
            startActivity(intent);
        });
        Log.d(TAG, "initView: 视图初始化完成");
        backImageButton = findViewById(R.id.imageButton_back);
        backImageButton.setOnClickListener((v) -> {
            finish();
        });
        shopCartImageButton = findViewById(R.id.imageButton_shop);
        shopCartImageButton.setOnClickListener((v) -> {
            Intent intent = new Intent(this, MainActivity.class);
            // 将MainActivity重新置于栈顶
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            intent.putExtra("type", MainActivity.FRAGMENT_SHOP_CART);
            startActivity(intent);
        });
    }

    private void initComment() {
        goodsComment = findViewById(R.id.goods_comment);
        goodsComment.setOnClickListener((v) -> {
            if (goods == null)
                return;
            Intent intent = new Intent(this, CommentActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("goodsId", goods.getId());
            intent.putExtra("isNewComment", false);
            startActivity(intent);
        });
    }

    private void initBottom() {
        addToShopCart = findViewById(R.id.textView_add_to_cart);
        buyNow = findViewById(R.id.textView_buy_now);
        addToShopCart.setOnClickListener((v) -> {
            createOrder(
                    orderId -> {
                        Toast.makeText(GoodsDetailActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(this, MainActivity.class);
                        // 将MainActivity重新置于栈顶
                        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        intent.putExtra("type", MainActivity.FRAGMENT_SHOP_CART);
                        startActivity(intent);
                    },
                    msg -> {
                        Toast.makeText(GoodsDetailActivity.this, "加入购物车失败 " + msg, Toast.LENGTH_SHORT).show();
                    });
        });
        buyNow.setOnClickListener((v) -> {
            createOrder(
                    orderId -> {
                        int[] orderIds = new int[1];
                        orderIds[0] = Integer.parseInt(orderId);
                        Log.d(TAG, "initBottom: 开始创建订单 " + orderIds[0]);
                        Intent intent = new Intent(this, OrderActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra(OrderActivity.TYPE, OrderActivity.TYPE_ORDER_CREATE);
                        intent.putExtra(OrderActivity.ORDER_IDS, orderIds);
                        startActivity(intent);
                    },
                    msg -> {
                        Toast.makeText(GoodsDetailActivity.this, "购买失败 " + msg, Toast.LENGTH_SHORT).show();
                    });
        });
    }

    void createOrder(HjmSuccessObjectCallBack<String> successObjectCallBack, HjmFailCallBack onFailCallBack) {
        if (goods == null)
            return;
        Order order = new Order();
        order.setGoodsNum(1);
        order.setGoodsId(goods.getId());
        // TODO:类型选择
        order.setGoodsType(String.valueOf(0));
        order.setState(1);
        orderService.createOrder(order, successObjectCallBack, onFailCallBack);
    }

    @Override
    void initData() {
        getGoods(goodsId);
        Log.d(TAG, "initData: 数据初始化完成");
    }

    @Override
    int getView() {
        return R.layout.activity_goods_detail;
    }

    /**
     * 初始化商品信息
     */
    void initGoodsIntro() {
        goodsIntro = findViewById(R.id.goods_intro);
        goodsStoreIntro = findViewById(R.id.goods_detail_store_intro);
        goodsStoreIntro.setOnClickListener((v) -> {
            if (goods != null) {
                Intent intent = new Intent(GoodsDetailActivity.this, StoreActivity.class);
                intent.putExtra("storeId", goods.getStore());
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化商品类型
     */
    void initGoodsType() {
        cellGoodsType = findViewById(R.id.cell_goods_detail_select);
//        cellGoodsType.setOnClickListener(v -> {
//            if (goods!=null&&goods.getType()!=null){
//                GoodsTypeListDialogFragment dialogFragment = GoodsTypeListDialogFragment.newInstance(goods.getType());
//                dialogFragment.setOnItemClickListener(new GoodsTypeListDialogFragment.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(String value, int position) {
//                        Log.d(TAG, "onItemClick: 选择了 "+value);
//                        setCellGoodsType(value);
//                        typeIndex = position;
//                    }
//                });
//                dialogFragment.show(getSupportFragmentManager(), "选择商品类型");
//            }
//        });
    }


    /**
     * 初始化商品信息所需要的WebView控件
     */
    void initWebView() {
        webViewGoodsDetail = findViewById(R.id.web_view_goods_detail);
        WebSettings settings = webViewGoodsDetail.getSettings();
        settings.setBuiltInZoomControls(false);//设定是否显示缩放按钮
        settings.setSupportZoom(false);//设定是否支持缩放
        settings.setJavaScriptEnabled(true);// 启用JavaScript支持
        settings.setDomStorageEnabled(true);

        webViewGoodsDetail.loadUrl("file:///android_asset/store_home.html");

        /**
         * WebChromeClient类用于辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等。
         * 打印webview日志
         */
        webViewGoodsDetail.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.d("WebView", "控制台信息: " + consoleMessage.message() + " -- From line " + consoleMessage.lineNumber());
                return true; // 表示您已经处理了这条消息
            }
        });

        /**
         * WebViewClient类用于辅助WebView处理各种通知、请求事件。
         * 页面渲染完成时执行
         */
        webViewGoodsDetail.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (goods != null) {
                    setGoodsContent(goods.getContent());
                } else {
                    isWebViewPageFinished = true;
                }
            }
        });
    }

    /**
     * 初始化商品banner
     */
    void initBanner() {
        banner = findViewById(R.id.banner);

        bannerList = new ArrayList<>();
        HomeBanner homeBanner = new HomeBanner();
        homeBanner.setImg(BitmapFactory.decodeResource(getResources(), R.drawable.yuan01));
        bannerList.add(homeBanner);
        homeBanner = new HomeBanner();
        homeBanner.setImg(BitmapFactory.decodeResource(getResources(), R.drawable.yuan02));
        bannerList.add(homeBanner);
        homeBanner = new HomeBanner();
        homeBanner.setImg(BitmapFactory.decodeResource(getResources(), R.drawable.yuan03));
        bannerList.add(homeBanner);

        // 设置适配器、设置指示器
        banner.setAdapter(new HomeBannerAdapter(bannerList)).setIndicator(new CircleIndicator(this));
    }

    /**
     * 获取商品信息
     *
     * @param id 商品id
     */
    void getGoods(int id) {
        goodsService.getGoodsDetail(id, (isSuccess, goods, msg) -> {
            if (isSuccess) {
                Log.d(TAG, "onGoodsDetail: 获取成功\n" + goods.toString());
                this.goods = goods;
                if (isWebViewPageFinished)
                    setGoodsContent(goods.getContent());
                setGoodsIntro(goods.getName(), String.valueOf(goods.getPrice()));
                setCellGoodsType(goods.getType()[typeIndex]);
                getStoreInfo(goods.getStore());
                // 商品信息获取完成后，去获取商品banner图片
                getBanner();
            } else {
                Log.e(TAG, "onFailure: 获取失败" + msg);
            }
        });
    }

    /**
     * 获取banner的图片
     */
    void getBanner() {
        goodsService.getBanner(goods.getBanner(),
                () -> {
                    bannerList = goodsService.getBannerList();
                    setBanner();
                });
    }

    /**
     * 设置商品banner
     */
    void setBanner() {
        Log.d(TAG, "checkAllImagesLoaded: 获取图片成功");
        // 设置适配器、设置指示器
        banner.setAdapter(new HomeBannerAdapter(bannerList)).setIndicator(new CircleIndicator(this));
    }

    /**
     * 获取商店信息
     *
     * @param storeId
     */
    void getStoreInfo(int storeId) {
        storeService.getStoreById(storeId,
                store -> {
                    setStoreInfo(store.getIcon(), store.getName());
                },
                msg -> {
                    Log.e(TAG, "onFailure: 获取商店信息失败" + msg);
                });
    }

    /**
     * 设置商店信息
     *
     * @param icon 商店icon id
     * @param name 商店名称
     */
    void setStoreInfo(int icon, String name) {
        storeService.getStoreIcon(icon, (isSuccess, bitmap, msg) -> {
            goodsStoreIntro.setStoreIcon(bitmap);
            goodsStoreIntro.setStoreName(name);
        });
    }

    /**
     * 设置商品详情页内容
     *
     * @param imageIds
     */
    private void setGoodsContent(int[] imageIds) {
        goodsService.setGoodsContent(imageIds, (isSuccess, javascriptCode, msg) -> {
            webViewGoodsDetail.evaluateJavascript(javascriptCode, null);
        });
    }

    private void setGoodsIntro(String name, String price) {
        mHandler.post(() -> {
            goodsIntro.setGoodsName(name);
            goodsIntro.setGoodsPrice(price);
        });
    }

    private void setCellGoodsType(String value) {
        mHandler.post(() -> {
            cellGoodsType.setText("已选择：" + value);
        });
    }
}